
import Placeholder from '../../../components/Placeholder';
import {articleListApi} from '../../directory/api'
import useFetch from '../../../hooks/useFetch';
import s from './index.module.scss'
import useAlbumAuth from '../../../hooks/useAlbumAuth';
import Taro from '@tarojs/taro';
import { ScrollView } from '@tarojs/components';
import getSystemInfo from "../../../utils/getSystemInfo";
import NavigationBar from "../../../components/NavigationBar";
import { useState } from 'react';

interface DirectoryProps {
  _id: string,
  title: string,
}

export default function Index(props: DirectoryProps) {
  const [current, setCurrent] = useState(0)
  const {_id, title} = props
  const auth = useAlbumAuth(_id)
  const systemInfo = getSystemInfo()
  const {
    navBarHeight = 0,
    statusBarHeight = 0,
    // @ts-ignore
    navbarHeight = 0,
    placeHolderHeight = 0
  } = systemInfo

  const {data, loading} = useFetch(articleListApi, _id)

  function jumptoWebview(item, index) {
    setCurrent(index)
    var _item = auth ? item : data[0]
    const { title, url} = _item

    const __title = encodeURIComponent(title)
    const __url = encodeURIComponent(url)

    let __path = `/pages/webview/index?url=${__url}&title=${__title}`;
    
    Taro.navigateTo({
      url: __path
    })
  }

  let root_height = systemInfo.screenHeight
  let scroll_height = root_height - navBarHeight - statusBarHeight - navbarHeight - placeHolderHeight / 2 - 85

  function __back() {
    Taro.eventCenter.trigger('home/modal/close')
  }

  return (
    <div id={s.root} style={{height: `${root_height}px`}}>
      <NavigationBar onBack={__back} title={title} />
      <Placeholder type='wholeNavigationBar' />
      <view id={s.wrapper}>
        {loading ? <view id={s.tip}>数据请求中...</view> : (
          <>
            <view className={s.top}>共<i className={s.italic}>{data.length}</i> 篇</view>
            <ScrollView scrollY style={{height: `${scroll_height}px`}} enhanced showScrollbar={false}>
              {data.length === 0 && (
                <view id={s.tip}>
                  内容创作中，目前暂无数据，请耐心等待！
                </view>
              )}
              {data.map((item, index) => (
                <div id={s.item} key={item._id} onClick={() => jumptoWebview(item, index)}>
                  <div id={s.index} className={current === index ? s.active : ''}>{index + 1}</div>
                  <div id={s.title}>{item.title}</div>
                </div>
              ))}
            </ScrollView>
          </>
        )}

      </view>
    </div>
  )
}
